﻿<%@ WebHandler Language="C#" Class="v_img_code" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

public class v_img_code : IHttpHandler ,IRequiresSessionState {
    /// <summary>
    /// 显示字符串的内容类型
    /// </summary>
    enum StrType
    {
        Number=0,
        EN=1,
        CN=2,
    }

    Graphics g;
    Bitmap newBitmap;
    string str;
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        /* 随机数字生成 */
        Random r = new Random();
        str = r.Next(100000, 999999).ToString();
        context.Session["VerificationImgCode"] = str;
        
        newBitmap = new Bitmap(75, 30, PixelFormat.Format32bppArgb);
        g = Graphics.FromImage(newBitmap);
        g.FillRectangle(new SolidBrush(Color.FromArgb(255, 255, 255, 255)), new Rectangle(0, 0, 75, 30));
        
        try
        {
            //干扰线数量
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                int x1 = random.Next(newBitmap.Width);
                int x2 = random.Next(newBitmap.Width);
                int y1 = random.Next(newBitmap.Height);
                int y2 = random.Next(newBitmap.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            
            Font strFont = new Font("Consolas", 14,FontStyle.Italic,GraphicsUnit.Pixel);
            g.DrawString(str, strFont, new SolidBrush(Color.Black), 10, 5);
            MemoryStream tempStream = new MemoryStream();
            newBitmap.Save(tempStream, ImageFormat.Png);
            context.Response.ClearContent();
            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(tempStream.ToArray());
            context.Response.End();
        }
        catch (Exception e)
        {
            context.Response.Write(e.ToString());
        }
        finally
        {
            if (g != null) g.Dispose();
            if (newBitmap != null) newBitmap.Dispose();
        }
        
        context.Response.Write("生成失败");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}